<template>
  <div class="dashboard">
    <div class="dashboard-header">
      <h2 class="page-title">网站总览</h2>
      <el-button 
        type="primary" 
        :loading="loading" 
        @click="refreshData"
        :icon="Refresh"
      >
        刷新数据
      </el-button>
    </div>
    
    <el-row :gutter="20">
      <!-- 数据卡片 -->
      <el-col :span="6" v-for="(card, index) in dataCards" :key="index">
        <el-card class="data-card" :body-style="{ padding: '20px' }" v-loading="loading">
          <div class="card-content">
            <el-icon class="card-icon" :class="card.type">
              <component :is="card.icon"></component>
            </el-icon>
            <div class="card-info">
              <div class="card-value">{{ card.value }}</div>
              <div class="card-label">{{ card.label }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card" v-loading="loading">
          <template #header>
            <div class="chart-header">
              <span>最近7天订单趋势</span>
              <el-radio-group v-model="orderTrendType" size="small">
                <el-radio-button label="count">订单数</el-radio-button>
                <el-radio-button label="amount">销售额</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" ref="orderTrendChart"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card" v-loading="loading">
          <template #header>
            <div class="chart-header">
              <span>药品销售排行</span>
              <el-select v-model="salesRankType" size="small" style="width: 120px">
                <el-option label="按销量" value="quantity" />
                <el-option label="按金额" value="amount" />
              </el-select>
            </div>
          </template>
          <div class="chart-container" ref="salesRankChart"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 最近订单列表 -->
    <el-card class="recent-orders" v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>最近订单</span>
          <el-button type="primary" link @click="$router.push('/admin/orders')">
            查看全部
          </el-button>
        </div>
      </template>
      <el-table :data="recentOrders" style="width: 100%">
        <el-table-column prop="orderId" label="订单号" width="180" />
        <el-table-column prop="customer" label="客户" width="120" />
        <el-table-column prop="amount" label="金额" width="120" />
        <el-table-column prop="status" label="状态" width="120">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" />
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { 
  ShoppingCart, 
  User, 
  FirstAidKit, 
  Document,
  Money,
  Refresh
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import axios from 'axios'
import { ElMessage } from 'element-plus'

export default {
  name: 'AdminDashboard',
  components: {
    ShoppingCart,
    User,
    FirstAidKit,
    Document,
    Money,
    Refresh
  },
  setup() {
    const orderTrendChart = ref(null)
    const salesRankChart = ref(null)
    const orderTrendType = ref('count')
    const salesRankType = ref('quantity')
    let orderTrendChartInstance = null
    let salesRankChartInstance = null
    const loading = ref(false)

    const dataCards = ref([
      {
        label: '总订单数',
        value: '0',
        icon: 'ShoppingCart',
        type: 'primary'
      },
      {
        label: '用户数量',
        value: '0',
        icon: 'User',
        type: 'success'
      },
      {
        label: '药品数量',
        value: '0',
        icon: 'FirstAidKit',
        type: 'warning'
      },
      {
        label: '总收入',
        value: '¥0',
        icon: 'Money',
        type: 'danger'
      }
    ])

    const recentOrders = ref([])

    // 获取仪表盘概览数据
    const fetchOverviewData = async () => {
      try {
        const [ordersRes, usersRes, medicinesRes] = await Promise.all([
          axios.get('http://localhost:3000/orders'),
          axios.get('http://localhost:3000/users'),
          axios.get('http://localhost:3000/medicines')
        ])

        const totalOrders = ordersRes.data.length
        const totalUsers = usersRes.data.length
        const totalMedicines = medicinesRes.data.length
        const totalIncome = ordersRes.data.reduce((sum, order) => sum + (order.total || 0), 0)

        dataCards.value = [
          {
            label: '总订单数',
            value: totalOrders.toLocaleString(),
            icon: 'ShoppingCart',
            type: 'primary'
          },
          {
            label: '用户数量',
            value: totalUsers.toLocaleString(),
            icon: 'User',
            type: 'success'
          },
          {
            label: '药品数量',
            value: totalMedicines.toLocaleString(),
            icon: 'FirstAidKit',
            type: 'warning'
          },
          {
            label: '总收入',
            value: `¥${totalIncome.toLocaleString()}`,
            icon: 'Money',
            type: 'danger'
          }
        ]
      } catch (error) {
        ElMessage.error('获取概览数据失败')
        console.error('获取概览数据失败:', error)
      }
    }

    // 获取订单趋势数据
    const fetchOrderTrendData = async () => {
      try {
        const { data: orders } = await axios.get('http://localhost:3000/orders')
        
        // 获取最近7天的日期
        const dates = Array.from({ length: 7 }, (_, i) => {
          const date = new Date()
          date.setDate(date.getDate() - i)
          return date.toISOString().split('T')[0]
        }).reverse()

        // 统计每天的订单数和销售额
        const counts = dates.map(date => {
          return orders.filter(order => order.createdAt?.split('T')[0] === date).length
        })

        const amounts = dates.map(date => {
          return orders
            .filter(order => order.createdAt?.split('T')[0] === date)
            .reduce((sum, order) => sum + (order.total || 0), 0)
        })

        updateOrderTrendChart({ dates, counts, amounts })
      } catch (error) {
        ElMessage.error('获取订单趋势数据失败')
        console.error('获取订单趋势数据失败:', error)
      }
    }

    // 获取销售排行数据
    const fetchSalesRankData = async () => {
      try {
        const { data: orders } = await axios.get('http://localhost:3000/orders')
        const { data: medicines } = await axios.get('http://localhost:3000/medicines')

        // 统计每个药品的销量和销售额
        const medicineStats = medicines.map(medicine => {
          const sales = orders.flatMap(order => order.items || [])
            .filter(item => item.id === medicine.id)
          
          const quantity = sales.reduce((sum, item) => sum + (item.quantity || 0), 0)
          const amount = sales.reduce((sum, item) => sum + (item.price || 0) * (item.quantity || 0), 0)

          return {
            name: medicine.name,
            quantity,
            amount
          }
        })

        // 按销量或销售额排序
        const sortedStats = medicineStats.sort((a, b) => {
          return salesRankType.value === 'quantity' 
            ? b.quantity - a.quantity 
            : b.amount - a.amount
        }).slice(0, 10)

        updateSalesRankChart({
          medicines: sortedStats.map(stat => stat.name),
          quantities: sortedStats.map(stat => stat.quantity),
          amounts: sortedStats.map(stat => stat.amount)
        })
      } catch (error) {
        ElMessage.error('获取销售排行数据失败')
        console.error('获取销售排行数据失败:', error)
      }
    }

    // 获取最近订单数据
    const fetchRecentOrders = async () => {
      try {
        const { data: orders } = await axios.get('http://localhost:3000/orders')
        const { data: users } = await axios.get('http://localhost:3000/users')

        // 获取最近5个订单
        const recentOrdersData = orders
          .sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
          .slice(0, 5)
          .map(order => {
            const user = users.find(u => u.id === order.userId)
            return {
              orderId: order.id,
              customer: user?.username || '未知用户',
              amount: order.total,
              status: getOrderStatusText(order.status),
              createTime: new Date(order.createdAt).toLocaleString('zh-CN')
            }
          })

        recentOrders.value = recentOrdersData
      } catch (error) {
        ElMessage.error('获取最近订单数据失败')
        console.error('获取最近订单数据失败:', error)
      }
    }

    // 获取订单状态文本
    const getOrderStatusText = (status) => {
      const statusMap = {
        'completed': '已完成',
        'pending': '待发货',
        'paid': '已付款',
        'cancelled': '已取消'
      }
      return statusMap[status] || status
    }

    // 更新订单趋势图表数据
    const updateOrderTrendChart = (data) => {
      if (!orderTrendChartInstance) return

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: data.dates,
          axisTick: {
            alignWithLabel: true
          }
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          name: orderTrendType.value === 'count' ? '订单数' : '销售额',
          type: 'line',
          smooth: true,
          data: orderTrendType.value === 'count' ? data.counts : data.amounts,
          itemStyle: {
            color: '#409EFF'
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: 'rgba(64,158,255,0.3)'
              },
              {
                offset: 1,
                color: 'rgba(64,158,255,0.1)'
              }
            ])
          }
        }]
      }

      orderTrendChartInstance.setOption(option)
    }

    // 更新销售排行图表数据
    const updateSalesRankChart = (data) => {
      if (!salesRankChartInstance) return

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value'
        },
        yAxis: {
          type: 'category',
          data: data.medicines,
          axisLabel: {
            interval: 0
          }
        },
        series: [{
          name: salesRankType.value === 'quantity' ? '销量' : '销售额',
          type: 'bar',
          data: salesRankType.value === 'quantity' ? data.quantities : data.amounts,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
              { offset: 0, color: '#83bff6' },
              { offset: 0.5, color: '#188df0' },
              { offset: 1, color: '#188df0' }
            ])
          }
        }]
      }

      salesRankChartInstance.setOption(option)
    }

    // 初始化订单趋势图表
    const initOrderTrendChart = () => {
      if (orderTrendChart.value) {
        orderTrendChartInstance = echarts.init(orderTrendChart.value)
        fetchOrderTrendData()
      }
    }

    // 初始化销售排行图表
    const initSalesRankChart = () => {
      if (salesRankChart.value) {
        salesRankChartInstance = echarts.init(salesRankChart.value)
        fetchSalesRankData()
      }
    }

    // 监听图表类型变化
    watch(orderTrendType, () => {
      fetchOrderTrendData()
    })

    watch(salesRankType, () => {
      fetchSalesRankData()
    })

    // 监听窗口大小变化
    const handleResize = () => {
      orderTrendChartInstance?.resize()
      salesRankChartInstance?.resize()
    }

    // 刷新所有数据
    const refreshData = async () => {
      loading.value = true
      try {
        await Promise.all([
          fetchOverviewData(),
          fetchOrderTrendData(),
          fetchSalesRankData(),
          fetchRecentOrders()
        ])
      } catch (error) {
        console.error('刷新数据失败:', error)
      } finally {
        loading.value = false
      }
    }

    const getStatusType = (status) => {
      const statusMap = {
        '已完成': 'success',
        '待发货': 'warning',
        '已付款': 'primary',
        '已取消': 'info'
      }
      return statusMap[status] || 'info'
    }

    onMounted(() => {
      refreshData()
      initOrderTrendChart()
      initSalesRankChart()
      window.addEventListener('resize', handleResize)
    })

    onUnmounted(() => {
      window.removeEventListener('resize', handleResize)
      orderTrendChartInstance?.dispose()
      salesRankChartInstance?.dispose()
    })

    return {
      dataCards,
      recentOrders,
      getStatusType,
      orderTrendChart,
      salesRankChart,
      orderTrendType,
      salesRankType,
      loading
    }
  }
}
</script>

<style scoped>
.dashboard {
  padding: 20px;
}

.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.data-card {
  margin-bottom: 20px;
  transition: all 0.3s;
}

.data-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
}

.card-content {
  display: flex;
  align-items: center;
}

.card-icon {
  font-size: 48px;
  margin-right: 20px;
  padding: 10px;
  border-radius: 8px;
}

.card-icon.primary {
  color: #409EFF;
  background: rgba(64,158,255,.1);
}

.card-icon.success {
  color: #67C23A;
  background: rgba(103,194,58,.1);
}

.card-icon.warning {
  color: #E6A23C;
  background: rgba(230,162,60,.1);
}

.card-icon.danger {
  color: #F56C6C;
  background: rgba(245,108,108,.1);
}

.card-info {
  flex: 1;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
}

.card-label {
  font-size: 14px;
  color: #909399;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 300px;
}

.recent-orders {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style> 